package com.jfinal.template.activerecord;

import java.util.Map;

import com.jfinal.template.Engine;
import com.jfinal.template.activerecord.sql.SqlKit;
import com.jfinal.template.source.ClassPathSourceFactory;

/**
 * @author: lbq
 * @email: 526509994@qq.com
 * @date: 2017/12/18
 */
public class SqlUtil {
    public static SqlKit sqlKit;
    private static boolean isStart = false;
    
    public static void start(String configName, boolean devMode, String sqlTemplatePath) {
        if (null == sqlKit) {
            sqlKit = new SqlKit(configName, devMode);
            // 从jar文件中读取sql
            Engine engine = sqlKit.getEngine();
            engine.setBaseTemplatePath(sqlTemplatePath);
            engine.setSourceFactory(new ClassPathSourceFactory());
            engine.addDirective("paraLike", ParaLikeDirective.class);
            engine.addDirective("paraIn", ParaInDirective.class);
            sqlKit.addSqlTemplate("all_sql.sql");
            sqlKit.parseSqlTemplate();
        }
    }
    
    private static void checkStart(String key) {
        if (isStart) return;
        if (null == sqlKit) {
            throw new RuntimeException("请先初始化SqlEnjoyPlugin... 调用sql失败:" + key);
        } else {
            isStart = true;
        }
    }
    
    public static String getSql(String key) {
        checkStart(key);
        return sqlKit.getSql(key);
    }
    
    public static SqlPara getSqlPara(String key, Map data) {
        checkStart(key);
        return sqlKit.getSqlPara(key, data);
    }
    
    public static SqlPara getSqlPara(String key, Object... paras) {
        checkStart(key);
        return sqlKit.getSqlPara(key, paras);
    }
}
